{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b96c9ef0-d757-4ccc-89c5-96d47383fe36",
   "metadata": {},
   "source": [
    "### Numpy练习题"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd9e5f44-af7d-4c80-b03b-69f4838607b8",
   "metadata": {},
   "source": [
    "打印当前Numpy版本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "dbed3cf5-3822-4077-9cf6-d2a76a00dda8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1ca0ce13-d245-4b9a-9086-3b51649b375b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.26.4\n"
     ]
    }
   ],
   "source": [
    "print(np.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd3548df-22df-43a3-9f28-62e15c84672a",
   "metadata": {},
   "source": [
    "构造一个全零矩阵，并打印其占用的内存大小"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "7ad4e5d1-23f0-4615-853c-edf78778d53e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200 bytes\n"
     ]
    }
   ],
   "source": [
    "z = np.zeros((5,5))\n",
    "print('%d bytes'%(z.size * z.itemsize))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ee7af19-9266-4459-b6e8-b0445d02111c",
   "metadata": {},
   "source": [
    "打印一个函数的帮助文档，比如numpy.add"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "263a36f6-8f82-4f4e-90f9-fccbc3fca66e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])\n",
      "\n",
      "Add arguments element-wise.\n",
      "\n",
      "Parameters\n",
      "----------\n",
      "x1, x2 : array_like\n",
      "    The arrays to be added.\n",
      "    If ``x1.shape != x2.shape``, they must be broadcastable to a common\n",
      "    shape (which becomes the shape of the output).\n",
      "out : ndarray, None, or tuple of ndarray and None, optional\n",
      "    A location into which the result is stored. If provided, it must have\n",
      "    a shape that the inputs broadcast to. If not provided or None,\n",
      "    a freshly-allocated array is returned. A tuple (possible only as a\n",
      "    keyword argument) must have length equal to the number of outputs.\n",
      "where : array_like, optional\n",
      "    This condition is broadcast over the input. At locations where the\n",
      "    condition is True, the `out` array will be set to the ufunc result.\n",
      "    Elsewhere, the `out` array will retain its original value.\n",
      "    Note that if an uninitialized `out` array is created via the default\n",
      "    ``out=None``, locations within it where the condition is False will\n",
      "    remain uninitialized.\n",
      "**kwargs\n",
      "    For other keyword-only arguments, see the\n",
      "    :ref:`ufunc docs <ufuncs.kwargs>`.\n",
      "\n",
      "Returns\n",
      "-------\n",
      "add : ndarray or scalar\n",
      "    The sum of `x1` and `x2`, element-wise.\n",
      "    This is a scalar if both `x1` and `x2` are scalars.\n",
      "\n",
      "Notes\n",
      "-----\n",
      "Equivalent to `x1` + `x2` in terms of array broadcasting.\n",
      "\n",
      "Examples\n",
      "--------\n",
      ">>> np.add(1.0, 4.0)\n",
      "5.0\n",
      ">>> x1 = np.arange(9.0).reshape((3, 3))\n",
      ">>> x2 = np.arange(3.0)\n",
      ">>> np.add(x1, x2)\n",
      "array([[  0.,   2.,   4.],\n",
      "       [  3.,   5.,   7.],\n",
      "       [  6.,   8.,  10.]])\n",
      "\n",
      "The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.\n",
      "\n",
      ">>> x1 = np.arange(9.0).reshape((3, 3))\n",
      ">>> x2 = np.arange(3.0)\n",
      ">>> x1 + x2\n",
      "array([[ 0.,  2.,  4.],\n",
      "       [ 3.,  5.,  7.],\n",
      "       [ 6.,  8., 10.]])\n",
      "Help on NoneType object:\n",
      "\n",
      "class NoneType(object)\n",
      " |  Methods defined here:\n",
      " |\n",
      " |  __bool__(self, /)\n",
      " |      True if self else False\n",
      " |\n",
      " |  __eq__(self, value, /)\n",
      " |      Return self==value.\n",
      " |\n",
      " |  __ge__(self, value, /)\n",
      " |      Return self>=value.\n",
      " |\n",
      " |  __gt__(self, value, /)\n",
      " |      Return self>value.\n",
      " |\n",
      " |  __hash__(self, /)\n",
      " |      Return hash(self).\n",
      " |\n",
      " |  __le__(self, value, /)\n",
      " |      Return self<=value.\n",
      " |\n",
      " |  __lt__(self, value, /)\n",
      " |      Return self<value.\n",
      " |\n",
      " |  __ne__(self, value, /)\n",
      " |      Return self!=value.\n",
      " |\n",
      " |  __repr__(self, /)\n",
      " |      Return repr(self).\n",
      " |\n",
      " |  ----------------------------------------------------------------------\n",
      " |  Static methods defined here:\n",
      " |\n",
      " |  __new__(*args, **kwargs)\n",
      " |      Create and return a new object.  See help(type) for accurate signature.\n",
      "\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(help(np.info(np.add)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b696f30-f3d7-46e6-b8f9-0f75d5fd81d3",
   "metadata": {},
   "source": [
    "创建一个10-49的数组，并将其倒序排列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "84338a38-c953-465a-94e0-2d6baea3b341",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33,\n",
       "       32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,\n",
       "       15, 14, 13, 12, 11, 10])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "liao_array = np.arange(10,50,1)\n",
    "liao_array = liao_array[::-1] ### 将数组倒序排列\n",
    "liao_array"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81574ca8-7615-4f61-80cd-0a7d29614c4c",
   "metadata": {},
   "source": [
    "找到一个数组中不为0的索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "ba8439e8-5164-4891-848b-b0468a3a9086",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([ 0,  1,  2,  3,  4,  9, 11], dtype=int64),)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.nonzero([1,2,3,4,5,0,0,0,0,1234,0,1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "854cf9cf-1134-4816-bd68-918e18f2babd",
   "metadata": {},
   "source": [
    "随机构造一个3*3矩阵，并打印其中最大与最小值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "f77fda2c-96dd-4caa-a47f-aa803e7b9656",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.07625319080248805"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "liao_array = np.random.random((3,3))\n",
    "liao_array.min()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "1ee5771a-8644-42ea-a63e-18c46cbc3420",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9624374684542032"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "liao_array.max()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2723ac37-06aa-438c-9e1d-f2c8b1c1399d",
   "metadata": {},
   "source": [
    "构造一个5*5的矩阵，令其值都为1，并在最外层加上一圈0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "0e73d4a4-caf3-46c0-9854-99bbababb014",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0., 0., 0., 0., 0., 0., 0.],\n",
       "       [0., 1., 1., 1., 1., 1., 0.],\n",
       "       [0., 1., 1., 1., 1., 1., 0.],\n",
       "       [0., 1., 1., 1., 1., 1., 0.],\n",
       "       [0., 1., 1., 1., 1., 1., 0.],\n",
       "       [0., 1., 1., 1., 1., 1., 0.],\n",
       "       [0., 0., 0., 0., 0., 0., 0.]])"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "liao_array = np.ones((5,5))\n",
    "liao_array = np.pad(liao_array,pad_width=1,mode='constant',constant_values=0)\n",
    "liao_array"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "4f505269-687a-4697-8ebc-e3b6f823e5c1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on _ArrayFunctionDispatcher in module numpy:\n",
      "\n",
      "pad(array, pad_width, mode='constant', **kwargs)\n",
      "    Pad an array.\n",
      "\n",
      "    Parameters\n",
      "    ----------\n",
      "    array : array_like of rank N\n",
      "        The array to pad.\n",
      "    pad_width : {sequence, array_like, int}\n",
      "        Number of values padded to the edges of each axis.\n",
      "        ``((before_1, after_1), ... (before_N, after_N))`` unique pad widths\n",
      "        for each axis.\n",
      "        ``(before, after)`` or ``((before, after),)`` yields same before\n",
      "        and after pad for each axis.\n",
      "        ``(pad,)`` or ``int`` is a shortcut for before = after = pad width\n",
      "        for all axes.\n",
      "    mode : str or function, optional\n",
      "        One of the following string values or a user supplied function.\n",
      "\n",
      "        'constant' (default)\n",
      "            Pads with a constant value.\n",
      "        'edge'\n",
      "            Pads with the edge values of array.\n",
      "        'linear_ramp'\n",
      "            Pads with the linear ramp between end_value and the\n",
      "            array edge value.\n",
      "        'maximum'\n",
      "            Pads with the maximum value of all or part of the\n",
      "            vector along each axis.\n",
      "        'mean'\n",
      "            Pads with the mean value of all or part of the\n",
      "            vector along each axis.\n",
      "        'median'\n",
      "            Pads with the median value of all or part of the\n",
      "            vector along each axis.\n",
      "        'minimum'\n",
      "            Pads with the minimum value of all or part of the\n",
      "            vector along each axis.\n",
      "        'reflect'\n",
      "            Pads with the reflection of the vector mirrored on\n",
      "            the first and last values of the vector along each\n",
      "            axis.\n",
      "        'symmetric'\n",
      "            Pads with the reflection of the vector mirrored\n",
      "            along the edge of the array.\n",
      "        'wrap'\n",
      "            Pads with the wrap of the vector along the axis.\n",
      "            The first values are used to pad the end and the\n",
      "            end values are used to pad the beginning.\n",
      "        'empty'\n",
      "            Pads with undefined values.\n",
      "\n",
      "            .. versionadded:: 1.17\n",
      "\n",
      "        <function>\n",
      "            Padding function, see Notes.\n",
      "    stat_length : sequence or int, optional\n",
      "        Used in 'maximum', 'mean', 'median', and 'minimum'.  Number of\n",
      "        values at edge of each axis used to calculate the statistic value.\n",
      "\n",
      "        ``((before_1, after_1), ... (before_N, after_N))`` unique statistic\n",
      "        lengths for each axis.\n",
      "\n",
      "        ``(before, after)`` or ``((before, after),)`` yields same before\n",
      "        and after statistic lengths for each axis.\n",
      "\n",
      "        ``(stat_length,)`` or ``int`` is a shortcut for\n",
      "        ``before = after = statistic`` length for all axes.\n",
      "\n",
      "        Default is ``None``, to use the entire axis.\n",
      "    constant_values : sequence or scalar, optional\n",
      "        Used in 'constant'.  The values to set the padded values for each\n",
      "        axis.\n",
      "\n",
      "        ``((before_1, after_1), ... (before_N, after_N))`` unique pad constants\n",
      "        for each axis.\n",
      "\n",
      "        ``(before, after)`` or ``((before, after),)`` yields same before\n",
      "        and after constants for each axis.\n",
      "\n",
      "        ``(constant,)`` or ``constant`` is a shortcut for\n",
      "        ``before = after = constant`` for all axes.\n",
      "\n",
      "        Default is 0.\n",
      "    end_values : sequence or scalar, optional\n",
      "        Used in 'linear_ramp'.  The values used for the ending value of the\n",
      "        linear_ramp and that will form the edge of the padded array.\n",
      "\n",
      "        ``((before_1, after_1), ... (before_N, after_N))`` unique end values\n",
      "        for each axis.\n",
      "\n",
      "        ``(before, after)`` or ``((before, after),)`` yields same before\n",
      "        and after end values for each axis.\n",
      "\n",
      "        ``(constant,)`` or ``constant`` is a shortcut for\n",
      "        ``before = after = constant`` for all axes.\n",
      "\n",
      "        Default is 0.\n",
      "    reflect_type : {'even', 'odd'}, optional\n",
      "        Used in 'reflect', and 'symmetric'.  The 'even' style is the\n",
      "        default with an unaltered reflection around the edge value.  For\n",
      "        the 'odd' style, the extended part of the array is created by\n",
      "        subtracting the reflected values from two times the edge value.\n",
      "\n",
      "    Returns\n",
      "    -------\n",
      "    pad : ndarray\n",
      "        Padded array of rank equal to `array` with shape increased\n",
      "        according to `pad_width`.\n",
      "\n",
      "    Notes\n",
      "    -----\n",
      "    .. versionadded:: 1.7.0\n",
      "\n",
      "    For an array with rank greater than 1, some of the padding of later\n",
      "    axes is calculated from padding of previous axes.  This is easiest to\n",
      "    think about with a rank 2 array where the corners of the padded array\n",
      "    are calculated by using padded values from the first axis.\n",
      "\n",
      "    The padding function, if used, should modify a rank 1 array in-place. It\n",
      "    has the following signature::\n",
      "\n",
      "        padding_func(vector, iaxis_pad_width, iaxis, kwargs)\n",
      "\n",
      "    where\n",
      "\n",
      "        vector : ndarray\n",
      "            A rank 1 array already padded with zeros.  Padded values are\n",
      "            vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:].\n",
      "        iaxis_pad_width : tuple\n",
      "            A 2-tuple of ints, iaxis_pad_width[0] represents the number of\n",
      "            values padded at the beginning of vector where\n",
      "            iaxis_pad_width[1] represents the number of values padded at\n",
      "            the end of vector.\n",
      "        iaxis : int\n",
      "            The axis currently being calculated.\n",
      "        kwargs : dict\n",
      "            Any keyword arguments the function requires.\n",
      "\n",
      "    Examples\n",
      "    --------\n",
      "    >>> a = [1, 2, 3, 4, 5]\n",
      "    >>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6))\n",
      "    array([4, 4, 1, ..., 6, 6, 6])\n",
      "\n",
      "    >>> np.pad(a, (2, 3), 'edge')\n",
      "    array([1, 1, 1, ..., 5, 5, 5])\n",
      "\n",
      "    >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))\n",
      "    array([ 5,  3,  1,  2,  3,  4,  5,  2, -1, -4])\n",
      "\n",
      "    >>> np.pad(a, (2,), 'maximum')\n",
      "    array([5, 5, 1, 2, 3, 4, 5, 5, 5])\n",
      "\n",
      "    >>> np.pad(a, (2,), 'mean')\n",
      "    array([3, 3, 1, 2, 3, 4, 5, 3, 3])\n",
      "\n",
      "    >>> np.pad(a, (2,), 'median')\n",
      "    array([3, 3, 1, 2, 3, 4, 5, 3, 3])\n",
      "\n",
      "    >>> a = [[1, 2], [3, 4]]\n",
      "    >>> np.pad(a, ((3, 2), (2, 3)), 'minimum')\n",
      "    array([[1, 1, 1, 2, 1, 1, 1],\n",
      "           [1, 1, 1, 2, 1, 1, 1],\n",
      "           [1, 1, 1, 2, 1, 1, 1],\n",
      "           [1, 1, 1, 2, 1, 1, 1],\n",
      "           [3, 3, 3, 4, 3, 3, 3],\n",
      "           [1, 1, 1, 2, 1, 1, 1],\n",
      "           [1, 1, 1, 2, 1, 1, 1]])\n",
      "\n",
      "    >>> a = [1, 2, 3, 4, 5]\n",
      "    >>> np.pad(a, (2, 3), 'reflect')\n",
      "    array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])\n",
      "\n",
      "    >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')\n",
      "    array([-1,  0,  1,  2,  3,  4,  5,  6,  7,  8])\n",
      "\n",
      "    >>> np.pad(a, (2, 3), 'symmetric')\n",
      "    array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])\n",
      "\n",
      "    >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')\n",
      "    array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])\n",
      "\n",
      "    >>> np.pad(a, (2, 3), 'wrap')\n",
      "    array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])\n",
      "\n",
      "    >>> def pad_with(vector, pad_width, iaxis, kwargs):\n",
      "    ...     pad_value = kwargs.get('padder', 10)\n",
      "    ...     vector[:pad_width[0]] = pad_value\n",
      "    ...     vector[-pad_width[1]:] = pad_value\n",
      "    >>> a = np.arange(6)\n",
      "    >>> a = a.reshape((2, 3))\n",
      "    >>> np.pad(a, 2, pad_with)\n",
      "    array([[10, 10, 10, 10, 10, 10, 10],\n",
      "           [10, 10, 10, 10, 10, 10, 10],\n",
      "           [10, 10,  0,  1,  2, 10, 10],\n",
      "           [10, 10,  3,  4,  5, 10, 10],\n",
      "           [10, 10, 10, 10, 10, 10, 10],\n",
      "           [10, 10, 10, 10, 10, 10, 10]])\n",
      "    >>> np.pad(a, 2, pad_with, padder=100)\n",
      "    array([[100, 100, 100, 100, 100, 100, 100],\n",
      "           [100, 100, 100, 100, 100, 100, 100],\n",
      "           [100, 100,   0,   1,   2, 100, 100],\n",
      "           [100, 100,   3,   4,   5, 100, 100],\n",
      "           [100, 100, 100, 100, 100, 100, 100],\n",
      "           [100, 100, 100, 100, 100, 100, 100]])\n",
      "\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(help(np.pad))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1ccd722-5fa8-4f4b-94e9-3896b8b4d5ce",
   "metadata": {},
   "source": [
    "构建一个shape为（6，7，8）的矩阵，并找到第100个元素的索引值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "7ee77617-052c-4ffb-8046-6371644f720b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, 5, 4)"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.unravel_index(100,(6,7,8))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6163a54c-9347-4d0a-aa12-71efc2115834",
   "metadata": {},
   "source": [
    "对一个5*5的矩阵做归一化操作(这里的归一化是指，将每个元素归到0-1之间)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "b37bd846-2e41-45c0-b57e-466a3e688540",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.42906773, 0.56899382, 0.90161786, 0.58640554, 0.91220493],\n",
       "       [1.        , 0.7511851 , 0.28112886, 0.39874815, 0.44522464],\n",
       "       [0.71990444, 0.85952482, 0.29080457, 0.02807387, 0.        ],\n",
       "       [0.86245835, 0.02517897, 0.85803196, 0.3472945 , 0.42184618],\n",
       "       [0.62921931, 0.15395856, 0.63771365, 0.24670894, 0.1970075 ]])"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "liao_array = np.random.random((5,5))\n",
    "liao_max = liao_array.max()\n",
    "liao_min = liao_array.min()\n",
    "liao_array = (liao_array-liao_min)/(liao_max - liao_min)\n",
    "liao_array"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bab161ce-fca5-4229-a502-6b31f64c935c",
   "metadata": {},
   "source": [
    "找到两个数组中相同的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "4e5a00b0-17ad-49ab-9e12-2909a77e9080",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[7 3 4 4 5 4 0 8 3 7]\n",
      "[7 6 6 0 7 4 2 4 3 9]\n",
      "[0 3 4 7]\n"
     ]
    }
   ],
   "source": [
    "z1 = np.random.randint(0,10,10)\n",
    "z2 = np.random.randint(0,10,10)\n",
    "print(z1)\n",
    "print(z2)\n",
    "print(np.intersect1d(z1,z2))  #用于计算两个数组 z1 和 z2 的交集（即找出两个数组中共同存在的元素）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "827c9b87-e9e5-4b61-82e4-f26a424eec58",
   "metadata": {},
   "source": [
    "得到今天  明天  昨天的日期"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "1ee9e179-31d9-41b6-a69d-54235bdbab93",
   "metadata": {},
   "outputs": [],
   "source": [
    "yesterday = np.datetime64('today','D') - np.timedelta64(1,'D')\n",
    "today = np.datetime64('today','D')\n",
    "tommorow = np.datetime64('today','D') + np.timedelta64(1,'D')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "346a4785-fbc2-47e8-8b2d-97822ca31cb9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.datetime64('2025-05-01')"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "yesterday"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "4c1dcf40-b374-4cf8-bf2f-1a0cc99c3ab7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.datetime64('2025-05-02')"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "today"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "5bf3122c-84ca-4131-8c4f-a4baaa1961e0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.datetime64('2025-05-03')"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tommorow"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adf1f982-498b-4c38-b1d2-c9f32350b929",
   "metadata": {},
   "source": [
    "得到一个月中所有的天"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4204cf5-b6b8-4f80-9a98-07c0cf17944d",
   "metadata": {},
   "source": [
    "np.arange('2025-05','2025-06',dtype='datetime64[D]')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af763dd4-f385-4cfa-bf42-088944d96c29",
   "metadata": {},
   "source": [
    "得到一个数的整数部分"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "9e13c30e-c822-4a66-b99d-45cb1f203fcc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([5., 1., 0., 3., 2., 7., 3., 4., 4., 7.])"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "z = np.random.uniform(0,10,10)\n",
    "np.floor(z) #生成一个包含 10 个随机浮点数的数组 z，然后对每个元素进行向下取整（floor）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0731ecf4-831d-4e1d-bd5f-71615b02d789",
   "metadata": {},
   "source": [
    "构造一个数组，让他不能被改变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "a638dc4d-ed63-4c06-8546-8ddc1fc8a9dc",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "assignment destination is read-only",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[83], line 3\u001b[0m\n\u001b[0;32m      1\u001b[0m z \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39mzeros(\u001b[38;5;241m5\u001b[39m)\n\u001b[0;32m      2\u001b[0m z\u001b[38;5;241m.\u001b[39mflags\u001b[38;5;241m.\u001b[39mwriteable \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mFalse\u001b[39;00m\n\u001b[1;32m----> 3\u001b[0m z[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m1\u001b[39m\n",
      "\u001b[1;31mValueError\u001b[0m: assignment destination is read-only"
     ]
    }
   ],
   "source": [
    "z = np.zeros(5)\n",
    "z.flags.writeable = False\n",
    "z[0]=1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89da221f-81c4-4e9e-8910-b4e3b7c33e56",
   "metadata": {},
   "source": [
    "打印大数据的部分值，全部值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "id": "8bda9c54-8f59-400b-b81a-77192d390cdc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0., 0., 0., ..., 0., 0., 0.],\n",
       "       [0., 0., 0., ..., 0., 0., 0.],\n",
       "       [0., 0., 0., ..., 0., 0., 0.],\n",
       "       ...,\n",
       "       [0., 0., 0., ..., 0., 0., 0.],\n",
       "       [0., 0., 0., ..., 0., 0., 0.],\n",
       "       [0., 0., 0., ..., 0., 0., 0.]])"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.set_printoptions(threshold=5)\n",
    "z = np.zeros((15,15))\n",
    "z"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "622f01ed-feac-4788-9a2a-8748e9251a23",
   "metadata": {},
   "source": [
    "找到在一个数组中，最接近一个数的索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "3007dd9c-89e3-498c-80cf-5357f33aab3a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12.292030901428951\n",
      "12\n"
     ]
    }
   ],
   "source": [
    "z = np.arange(100)\n",
    "v = np.random.uniform(0,100) ### 随机的浮点数\n",
    "print(v)\n",
    "index = (np.abs(z-v)).argmin() #最小值的索引\n",
    "print(z[index])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2257eb4-f236-4ebe-b2ac-384e25e843e3",
   "metadata": {},
   "source": [
    "32位float类型和32位int类型转换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "ac90329e-e7cb-481a-8ef9-c26099bc5e26",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "int32\n",
      "float32\n"
     ]
    }
   ],
   "source": [
    "z =np.arange(10,dtype=np.int32)\n",
    "print(z.dtype)\n",
    "z = z.astype(np.float32)\n",
    "print(z.dtype)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "945b201d-5097-4d49-a461-d97722bf6f33",
   "metadata": {},
   "source": [
    "打印数组元素位置坐标与数值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "6de75c1b-9f64-4472-b1d1-db15da155efb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, 0) 0\n",
      "(0, 1) 1\n",
      "(0, 2) 2\n",
      "(1, 0) 3\n",
      "(1, 1) 4\n",
      "(1, 2) 5\n",
      "(2, 0) 6\n",
      "(2, 1) 7\n",
      "(2, 2) 8\n"
     ]
    }
   ],
   "source": [
    "z = np.arange(9).reshape(3,3) #创建一个3X3的数组，元素的值在0~8\n",
    "for index,value in np.ndenumerate(z): #使用 np.ndenumerate() 遍历数组，取得值和索引\n",
    "    print(index,value)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13ebbe54-d326-479e-8417-e47dd0b7e9b2",
   "metadata": {},
   "source": [
    "按照数组的某一列进行排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "id": "99496e04-acec-4ae1-8563-15247c0e34ab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 3 3]\n",
      " [8 2 0]\n",
      " [1 6 7]]\n",
      "[[8 2 0]\n",
      " [1 3 3]\n",
      " [1 6 7]]\n"
     ]
    }
   ],
   "source": [
    "z = np.random.randint(0,10,(3,3))\n",
    "print(z)\n",
    "print(z[z[:,1].argsort()]) # 按第1列进行排序"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "563cd081-7d49-4337-8077-3924f19716c5",
   "metadata": {},
   "source": [
    "统计数组中每个数值出现的次数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "id": "db74d4e3-5b95-41cf-b168-2e2c50c447e9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 3, 2, ..., 0, 0, 1], dtype=int64)"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "z = np.array([1,1,1,2,2,3,3,4,5,8])\n",
    "np.bincount(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b224f0b-e60a-446e-b31d-0fcee42f6460",
   "metadata": {},
   "source": [
    "如何对一个四维数组的最后两维来求和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "id": "8e46c5a5-3205-44a1-a3c0-f3b97fabf224",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[57, 77, 68, 61],\n",
       "       [64, 81, 78, 66],\n",
       "       [64, 81, 79, 90],\n",
       "       [68, 82, 57, 65]])"
      ]
     },
     "execution_count": 118,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "z = np.random.randint(0,10,(4,4,4,4))\n",
    "res = z.sum(axis=(-2,-1))\n",
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aed5a995-f782-4c47-b535-37abf69a2aca",
   "metadata": {},
   "source": [
    "交换矩阵中的两行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "id": "fa1adb17-fdfe-4590-ba62-fec689bd5f34",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3  4]\n",
      " [ 5  6  7  8  9]\n",
      " [10 11 12 13 14]\n",
      " [15 16 17 18 19]\n",
      " [20 21 22 23 24]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[10, 11, 12, 13, 14],\n",
       "       [ 5,  6,  7,  8,  9],\n",
       "       [ 0,  1,  2,  3,  4],\n",
       "       [15, 16, 17, 18, 19],\n",
       "       [20, 21, 22, 23, 24]])"
      ]
     },
     "execution_count": 125,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "z = np.arange(25).reshape(5,5)\n",
    "print(z)\n",
    "z[[0,1]] = z[[1,0]] #第0行与第1行交换\n",
    "z"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5ecd9ea-601f-4e70-aacd-af5d43a72412",
   "metadata": {},
   "source": [
    "找到一个数组中最常出现的数字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 130,
   "id": "9e276394-87fb-4929-b96e-609d38b6e2f3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "z = np.random.randint(0,10,50)\n",
    "print(np.bincount(z).argmax())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ccad8d9-ba1e-4b3d-aa16-fbf16376740e",
   "metadata": {},
   "source": [
    "快速查找 TOP K （最大的K个数）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "id": "ccfe968c-a854-4bc9-baa6-829666875e23",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[9998 9997 9999 9996 9995]\n"
     ]
    }
   ],
   "source": [
    "z = np.arange(10000)\n",
    "np.random.shuffle(z) #随机打乱 z\n",
    "n = 5\n",
    "print(z[np.argpartition(-z,n)[:n]])\n",
    "## 找出最大的5个数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5114674-ecf6-4924-aed1-a38c659552fa",
   "metadata": {},
   "source": [
    "去除掉一个数组中，所有元素都相同的数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "id": "bd213181-d33a-4d9f-9f89-e6eb42fd9225",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 0, 0],\n",
       "       [0, 0, 0],\n",
       "       [0, 0, 0],\n",
       "       ...,\n",
       "       [1, 2, 2],\n",
       "       [1, 1, 0],\n",
       "       [0, 2, 1]])"
      ]
     },
     "execution_count": 153,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## np.set_printoptions(threshold=np.nan) np.nan已经被弃用\n",
    "np.set_printoptions(threshold=None)\n",
    "z = np.random.randint(0,3,(10,3))\n",
    "z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "id": "bd985941-2865-43b7-a290-770ce603f134",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ True  True  True ... False False False]\n"
     ]
    }
   ],
   "source": [
    "e = np.all(z[:,1:] == z[:,:-1],axis = 1)\n",
    "print(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "bdf803e2-de9c-48b3-b053-06481741c963",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 157,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = np.array([1,2,3,4])\n",
    "b = np.array([1,2,3,5])\n",
    "np.all(a == b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "7a2fbc3f-d40a-4832-966e-7015c968f5dc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 159,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.any(a == b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28b887c6-ebb4-4e26-835b-59c1f4d75e82",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
